import codecs
import pandas as pd
import re


def replace_first_match(content, pattern, replacement):
    # 使用正则表达式确保只替换第一个匹配项
    new_content = re.sub(pattern, replacement, content, count=1)
    return new_content


def buildOptionsProject(url):
    # with open('./output/options.txt', 'r', encoding='utf-8') as read_file:
    #     print("build txt success")
    # 读取Excel文件并转换为DataFrame对象
    df = pd.read_excel(url, sheet_name='Sheet1')
    project_names = df['项目名称'].tolist()

    # 获取所属科目列的数据
    subjects = df['所属科目'].tolist()

    # 获取代课老师列的数据
    teachers = df['代课老师'].tolist()

    # 获取项目 BGM 列的数据
    bgms = df['项目bgm'].tolist()

    # 打印数据
    for i in range(len(project_names)):
        print("项目名称:", project_names[i])
        print("所属科目:", subjects[i])
        print("代课老师:", teachers[i])
        print("项目 BGM:", bgms[i])
        print("------------------------------")

    # 读取文件内容
    with open('./Examples/optionsExample.txt', 'r', encoding='utf-8') as read_file:
        content = read_file.read()

    # 处理内容
    new_content = replace_first_match(content, "AAAAAAA", teachers[0])
    new_content = replace_first_match(new_content, "BBBBBB", subjects[0])
    new_content = replace_first_match(new_content, "PBLDemoTest", project_names[0])

    # 写回文件（重新打开文件，这次使用写入模式）
    with open('./output/options.txt', 'w', encoding='utf-8', errors='ignore') as write_file:
        write_file.write(new_content)


if __name__ == '__main__':
    url = "./Examples/wanDan.xlsx"
    buildOptionsProject(url)


